import type { PluginLifecycle, PluginContext } from '@bai-hu/plugin-sdk'
import React, { useEffect, useState } from 'react'

const Panel: React.FC<{ onTick: (n: number) => void; title?: string; refreshInterval?: number; showLegend?: boolean; theme?: 'light' | 'dark' }> = ({ title = 'Data Panel', refreshInterval = 5, showLegend = true, theme = 'light', onTick }) => {
  const [tick, setTick] = useState(0)
  useEffect(() => {
    const t = setInterval(() => setTick((x) => x + 1), refreshInterval * 1000)
    return () => clearInterval(t)
  }, [refreshInterval])
  useEffect(() => {
    onTick(tick)
  }, [tick])
  return (
    <div className="p-3 border rounded" style={{ background: 'var(--plugin-bg)', color: 'var(--plugin-fg)' }}>
      <div className="font-semibold">{title}</div>
      <div className="text-sm opacity-80">tick: {tick}</div>
      {showLegend && <div className="mt-2 text-xs opacity-70">Legend: ...</div>}
      <div className="text-xs mt-1">theme: {theme}</div>
    </div>
  )
}

export const activate: PluginLifecycle<any, any, React.FC>['activate'] = async (ctx: PluginContext) => {
  const cfg = (ctx.manifest as any).config || {}
  return () => {
    const [theme, setTheme] = useState<'light' | 'dark'>('light')
    useEffect(() => {
      const off = ctx.events.on('theme:change' as any, (p: any) => setTheme(p.theme))
      return off
    }, [])
    return <Panel {...cfg} theme={theme} onTick={(n) => ctx.events.emit('data:tick' as any, { tick: n })} />
  }
}

